package com.yzs.exam.config.spring.security;

import com.yzs.exam.entity.User;
import com.yzs.exam.entity.UserEventLog;
import com.yzs.exam.event.UserEvent;
import com.yzs.exam.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * 注销成功处理器
 * 获得UserDetail的用户信息 -- 到数据库查找用户信息 -- 生成用户日志 -- 发布用户日志事件
 * @author yzs
 * @create 2021-03-21 12:07
 */
@Component
@AllArgsConstructor
public class RestLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {

    private final ApplicationEventPublisher eventPublisher;
    private final UserService userService;


    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        org.springframework.security.core.userdetails.User SpringUser = (org.springframework.security.core.userdetails.User) authentication.getPrincipal();
        if (SpringUser != null){
            User user = userService.getUserByUserName(SpringUser.getUsername());
            UserEventLog userEventLog = new UserEventLog(user.getId(), user.getUserName(), user.getRealName(), new Date());
            userEventLog.setContent(user.getUserName() + " 登出了智能考试系统");
            eventPublisher.publishEvent(new UserEvent(userEventLog));
        }
    }
}
